package kata08;

import kata06.Trie;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class WordContainTwoWords {
    private Trie tire;
    private Set<String> lengthIsSixWords;


    public WordContainTwoWords() {
        this.tire = new Trie();
        lengthIsSixWords = new HashSet<>();
    }

    //1.读文件
    public List<String> getWordsLessThenFiveByReadFile(String filePath) throws IOException {
        String file = this.getClass().getClassLoader().getResource(filePath).getFile();
        FileReader reader = new FileReader(file);
        BufferedReader br = new BufferedReader(reader);
        String strLine;
        List<String> infos = new ArrayList<>();
        while ((strLine = br.readLine()) != null) {
            if(strLine.trim().length() == 6){
                lengthIsSixWords.add(strLine);
            }
            else if (strLine.trim().length() < 6) {
                infos.add(strLine);
            }
        }
        return  infos;
    }

    // 数据加入字典树
    public void AddToTrie (List<String> words) {
        for (String word : words){
            tire.insert(word);
        }
    }

    //3.判断单词分割后  在字典树中否存在
    public boolean isContainTwoWords(String word){
        int length = word.length();
        for(int i = 0; i < length; i++){
            if(tire.search(word.substring(0,(i+1))) && tire.search(word.substring((i+1),length))){
                return true;
            }
        }
        return false;
    }

    //4.获取字段数中符合要求的单词列表
    public List<String> getWordContainTwoWords(){
        return lengthIsSixWords.stream().filter(this::isContainTwoWords).collect(Collectors.toList());
    }

}
